package com.dlwx.firefighting.activity;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dlwx.firefighting.R;
import com.dlwx.firefighting.adapter.ProductAdapter;
import com.dlwx.firefighting.adapter.RecommentHorizonAdapter;
import com.dlwx.firefighting.bean.BaseBean;
import com.dlwx.firefighting.bean.GoodsBean;
import com.dlwx.firefighting.bean.GoodsDetailBean;
import com.dlwx.firefighting.config.Constant;
import com.dlwx.firefighting.utils.BuyNowDialog;
import com.dlwx.firefighting.utils.DealResult;
import com.dlwx.firefighting.utils.glide.GlideImageLoaderForBanner;
import com.dlwx.firefighting.views.GridSpacingItemDecoration;
import com.dlwx.firefighting.widget.CircleImageView;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.view.CommonHeader;
import com.google.gson.reflect.TypeToken;
import com.iarcuschin.simpleratingbar.SimpleRatingBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class GoodsDetailsActivity extends BaseActivity {
    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_mall)
    TextView tvMall;
    @BindView(R.id.tv_detail)
    TextView tvDetail;
    @BindView(R.id.ll_mall)
    LinearLayout llMall;
    @BindView(R.id.title_right_one_btn)
    ImageView titleRightOneBtn;
    @BindView(R.id.rl_bar)
    RelativeLayout rlBar;

    Banner banner;
    @BindView(R.id.rl_banner)
    RelativeLayout rlBanner;
    TextView goods_name,tv_price,tv_oldprice,tv_sale;

    @BindView(R.id.tv_vip)
    TextView tvVip;
    @BindView(R.id.head_img)
    CircleImageView headImg;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.rating_bar)
    SimpleRatingBar ratingBar;
    @BindView(R.id.tv_des)
    TextView tvDes;
    @BindView(R.id.content)
    TextView content;
    @BindView(R.id.image_recyclerView)
    RecyclerView imageRecyclerView;
    RecyclerView recomRecyclerView;
    @BindView(R.id.image_kefu)
    ImageView imageKefu;
    @BindView(R.id.ll_kefu)
    LinearLayout llKefu;
    @BindView(R.id.image_cart)
    ImageView imageCart;
    @BindView(R.id.ll_cart)
    LinearLayout llCart;
    @BindView(R.id.img_collect)
    ImageView imgCollect;
    @BindView(R.id.ll_collect)
    LinearLayout llCollect;
    @BindView(R.id.tv_addcart)
    TextView tvAddcart;
    @BindView(R.id.tv_buy)
    TextView tvBuy;
    @BindView(R.id.rl_comment)
    RelativeLayout rlComment;
    @BindView(R.id.mall_recyclerView)
    LRecyclerView mallRecyclerView;
    @BindView(R.id.detail_recyclerView)
    LRecyclerView detailRecyclerView;
    @BindView(R.id.rl_slide)
    RelativeLayout rlSlide;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    private ProductAdapter productAdapter;
    private int mall_height, detail_height;
    private RecommentHorizonAdapter recommentHorizonAdapter;
    private String id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goodsdetails1);
        ButterKnife.bind(this);
        id=getIntent().getStringExtra("id");
        initView();
        initBanner();
        initRecomment();
        getGoodsDetail();
        getRecoment();
    }

    private void getRecoment() {

        OkGo.<String>post(Constant.detail_hot)
                .tag(this)
                .params("id",id)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        List<GoodsBean> beans=DealResult.getInstance().dealDatas(GoodsDetailsActivity.this,response
                                ,new TypeToken<BaseBean<GoodsBean,GoodsBean>>(){}.getType());
                        recommentHorizonAdapter.addAll(beans);
                    }
                });
    }

    private void getGoodsDetail() {
        OkGo.<String>post(Constant.detail_product)
                .tag(this)
                .params("id",id)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        GoodsBean bean=DealResult.getInstance().dealData(GoodsDetailsActivity.this,response
                                ,new TypeToken<BaseBean<GoodsBean,GoodsBean>>(){}.getType());
                        goods_name.setText(bean.getProductName());
                        tv_price.setText(getString(R.string.rmb)+bean.getSalePrice());
                        tv_sale.setText("销量："+bean.getSaleNum());
                    }
                });
    }

    private void initView() {
        productAdapter = new ProductAdapter(this);
        mallRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        LRecyclerViewAdapter lRecyclerViewAdapter = new LRecyclerViewAdapter(productAdapter);
        mallRecyclerView.setAdapter(lRecyclerViewAdapter);
        CommonHeader header = new CommonHeader(this, R.layout.head_googs_details);
        recomRecyclerView= (RecyclerView) header.findViewById(R.id.recom_recyclerView);
        goods_name= (TextView) header.findViewById(R.id.goods_name);
        banner= (Banner) header.findViewById(R.id.banner);
        tv_price= (TextView) header.findViewById(R.id.tv_price);
        tv_oldprice= (TextView) header.findViewById(R.id.tv_oldprice);
        tv_sale= (TextView) header.findViewById(R.id.tv_sale);
        lRecyclerViewAdapter.addHeaderView(header);
        mallRecyclerView.setLoadMoreEnabled(true);
        mallRecyclerView.setPullRefreshEnabled(false);
        mallRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                switchButton(1);
                mallRecyclerView.refreshComplete(0);
            }
        });
//商品详情
        detailRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        LRecyclerViewAdapter mall_lRecyclerViewAdapter = new LRecyclerViewAdapter(productAdapter);
        detailRecyclerView.setAdapter(mall_lRecyclerViewAdapter);
        CommonHeader mall_header = new CommonHeader(this, R.layout.foot_googs_details);
        mall_lRecyclerViewAdapter.addHeaderView(mall_header);
        detailRecyclerView.setLoadMoreEnabled(false);
        detailRecyclerView.setPullRefreshEnabled(true);
        detailRecyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                switchButton(0);
                detailRecyclerView.refreshComplete(0);

            }
        });
        ViewTreeObserver vto1 = mallRecyclerView.getViewTreeObserver();
        vto1.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mallRecyclerView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                mall_height = mallRecyclerView.getHeight();
            }
        });
//
        ViewTreeObserver vto2 = detailRecyclerView.getViewTreeObserver();
        vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                detailRecyclerView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                detail_height = detailRecyclerView.getHeight();
            }
        });

    }



    private void initBanner() {
        List<String> banners = new ArrayList<>();
        banners.add("http://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E5%9B%BE%E7%89%87&step_word=&hs=0&pn=55&spn=0&di=15808602810&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=undefined&cs=17572568%2C2472534097&os=731670874%2C435174537&simid=3373174683%2C328309282&adpicid=0&lpn=0&ln=1986&fr=&fmq=1521626790475_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=&objurl=http%3A%2F%2Fpic41.nipic.com%2F20140518%2F18521768_133448822000_2.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Fooo_z%26e3Bgtrtv_z%26e3Bv54AzdH3Ffi5oAzdH3F8anddcnl_z%26e3Bip4s&gsm=0&rpstart=0&rpnum=0");
        banners.add("http://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E5%9B%BE%E7%89%87&step_word=&hs=0&pn=55&spn=0&di=15808602810&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=undefined&cs=17572568%2C2472534097&os=731670874%2C435174537&simid=3373174683%2C328309282&adpicid=0&lpn=0&ln=1986&fr=&fmq=1521626790475_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=&objurl=http%3A%2F%2Fpic41.nipic.com%2F20140518%2F18521768_133448822000_2.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Fooo_z%26e3Bgtrtv_z%26e3Bv54AzdH3Ffi5oAzdH3F8anddcnl_z%26e3Bip4s&gsm=0&rpstart=0&rpnum=0");
        if (banners.isEmpty()) {
            return;
        }
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
            }
        });
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setImageLoader(new GlideImageLoaderForBanner());
        banner.setImages(banners);
        banner.start();
    }

    private void initRecomment() {
        recommentHorizonAdapter = new RecommentHorizonAdapter(this, new ArrayList<GoodsBean>());
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recomRecyclerView.addItemDecoration(new GridSpacingItemDecoration(1,20,true));
        recomRecyclerView.setLayoutManager(manager);
        recomRecyclerView.setAdapter(recommentHorizonAdapter);
    }

    private int page = 1;
    private int requestNum = 10;
    private int count = 0;

    private void getDatas(String id) {
//        OkGo.<String>post(Constant.DETAIL_GOODS)
//                .tag(this)
//                .params("goods_id", id)
//                .params("user_id", userId)
//                .execute(new StringCallback() {
//                    @Override
//                    public void onSuccess(Response<String> response) {
//                        DealResult dealResult = new DealResult();
//                        List<GoodsDetailBean> beans = dealResult.deal(GoodsDetailsActivity.this, response, new TypeToken<BaseBean<GoodsDetailBean>>() {
//                        }.getType());
//                        setDatas(beans);
//                    }
//
//                    @Override
//                    public void onError(Response<String> response) {
//                        ToastUtils.toastForShort(GoodsDetailsActivity.this, getString(R.string.bad_net));
//                        super.onError(response);
//                    }
//                });
    }


    private int inventroy = 0;

    private void setDatas(List<GoodsDetailBean> beans) {
    }

    private void initBanner(List<String> banners) {
    }


    private void addCart(String num, String specid) {
//        OkGo.<String>post(Constant.ADD_CART)
//                .tag(this)
//                .params("user", userId)
//                .params("goods_id", goodsId)
//                .params("num", num)
//                .params("specid", specid)
//                .execute(new StringCallback() {
//                    @Override
//                    public void onSuccess(Response<String> response) {
//                        String res = response.body().toString().trim();
//                        if (TextUtils.isEmpty(res)) {
//                            ToastUtils.toastForShort(GoodsDetailsActivity.this, "添加购物车失败");
//                            return;
//                        } else {
//                            BaseBean bean = new Gson().fromJson(res, BaseBean.class);
//                            if (bean.getStatus() == Constant.SUCESS) {
//                                ToastUtils.toastForShort(GoodsDetailsActivity.this, "添加购物车成功");
//                            } else {
//                                ToastUtils.toastForShort(GoodsDetailsActivity.this, bean.getMsg());
//                            }
//                        }
//
//                    }
//
//                    @Override
//                    public void onError(Response<String> response) {
//                        ToastUtils.toastForShort(GoodsDetailsActivity.this, getString(R.string.bad_net));
//                        super.onError(response);
//                    }
//                });
    }

    private void collectGoods() {
//        返回type1  ；2
//        OkGo.<String>post(Constant.COLLECT_GOODS)
//                .tag(this)
//                .params("user_id", userId)
//                .params("goods_id", goodsId)
//                .execute(new StringCallback() {
//                    @Override
//                    public void onSuccess(Response<String> response) {
//                        DealResult dealResult = new DealResult();
//                        List<StatusBean> beans = dealResult.deal(GoodsDetailsActivity.this, response, new TypeToken<BaseBean<StatusBean>>() {
//                        }.getType());
//                        if (beans.isEmpty()) {
//                            return;
//                        }
//                        int type = beans.get(0).getType();
//                        if (type == 1) {
//                            collectImg.setImageResource(R.mipmap.details_collect);
//                            ToastUtils.toastForShort(GoodsDetailsActivity.this, "收藏成功！");
//                        } else if (type == 2) {
//                            collectImg.setImageResource(R.mipmap.details_collect_un);
//                            ToastUtils.toastForShort(GoodsDetailsActivity.this, "取消收藏成功！");
//                        }
//                    }
//
//                    @Override
//                    public void onError(Response<String> response) {
//                        ToastUtils.toastForShort(GoodsDetailsActivity.this, getString(R.string.bad_net));
//                        super.onError(response);
//                    }
//                });
    }

    private void addOrderInfo(String goodsId, String num, float total) {
//        DialogUtils.showProgressDlg(this, "");
//        OkGo.<String>post(Constant.addOrderInfo)
//                .tag(this)
//                .params("userid", userId)
//                .params("goods_id", goodsId)
//                .params("total", total)
//                .params("num", num)
//                .execute(new StringCallback() {
//                    @Override
//                    public void onSuccess(Response<String> response) {
//                        DialogUtils.stopProgressDlg();
//                        DealResult dealResult = new DealResult();
//                        List<OrderNowBean> beans = dealResult.deal(GoodsDetailsActivity.this, response, new TypeToken<BaseBean<OrderNowBean>>() {
//                        }.getType());
//                        if (!beans.isEmpty()) {
//                            Intent i = new Intent(GoodsDetailsActivity.this, PayActivity.class);
//                            i.putExtra("bean", beans.get(0));
//                            startActivity(i);
//                        }
//                    }
//
//                    @Override
//                    public void onError(Response<String> response) {
//                        DialogUtils.stopProgressDlg();
//                        ToastUtils.toastForShort(GoodsDetailsActivity.this, getString(R.string.bad_net));
//                        super.onError(response);
//                    }
//                });
    }

    public void refreshData(int position, boolean isZan, String zanNum) {
    }

    @OnClick({R.id.title_left_one_btn, R.id.tv_mall, R.id.tv_detail, R.id.ll_mall, R.id.title_right_one_btn
            , R.id.ll_kefu, R.id.ll_collect, R.id.ll_cart, R.id.tv_addcart, R.id.tv_buy, R.id.rl_comment})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_one_btn:
                this.finish();
                break;
            case R.id.tv_mall:
                switchButton(0);
                break;
            case R.id.tv_detail:
                switchButton(1);
                break;
            case R.id.ll_mall:
                break;
            case R.id.title_right_one_btn:
                break;
            case R.id.ll_kefu:
                break;
            case R.id.ll_cart:
                break;
            case R.id.ll_collect:
                break;
            case R.id.rl_comment:
                startActivity(new Intent(this, CommentListActivity.class));
                break;
            case R.id.tv_addcart:
                break;
            case R.id.tv_buy:
                BuyNowDialog dialog = new BuyNowDialog(this, null, null);
                dialog.show();
                break;
        }
    }

    private void switchButton(int i) {
        switch (i){
            case 0:
                tvMall.setBackground(null);
                tvMall.setTextColor(ContextCompat.getColor(this,R.color.black));
                tvDetail.setBackgroundResource(R.drawable.shape_black_bg_right);
                tvDetail.setTextColor(ContextCompat.getColor(this,R.color.white));
                slideView(mallRecyclerView,-mall_height,0);
                slideView(detailRecyclerView,0,detail_height);
                break;
            case 1:
                tvMall.setBackgroundResource(R.drawable.shape_black_bg_left);
                tvMall.setTextColor(ContextCompat.getColor(this,R.color.white));
                tvDetail.setBackground(null);
                tvDetail.setTextColor(ContextCompat.getColor(this,R.color.black));
                slideView(mallRecyclerView,0,-mall_height);
                slideView(detailRecyclerView,detail_height,0);
                break;
        }
    }

    private void slideView(View view,int start ,int end) {
        ObjectAnimator anim = ObjectAnimator.ofFloat(view, "translationY", start, end);
        anim.setRepeatCount(0);
        anim.setDuration(500);
        anim.start();
    }
}
